    
/**   
 * 文件名：com.xingfu999.ssm.ConcurrentHashMapDemo.java   
 */   
    
package cn.tx.common.concurrent;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

    
 /**   
 * 此类描述的是:
 * @author: cuixinfu@timidata.com
 * @version: 1.0 
 * @date:2017年8月22日 下午3:31:31  
 * Copyright xingfu999 Corporation 2017    
 */

public class ConcurrentHashMapTest {
    /**   
     * 此方法描述的是： ConcurrentHashMap 测试
     * 源代码地址:http://blog.csdn.net/zero__007/article/details/49833819
     * @author: cuixinfu@timidata.com void
     */
    public static void main(String[] args){
        demo1();
//        demo2();
    }
    public static void demo1() {  
        final Map<String, Integer> count = new ConcurrentHashMap<>();  
        final CountDownLatch endLatch = new CountDownLatch(2);  
        Runnable task = new Runnable() {  
            @Override  
            public void run() {  
                for (int i = 0; i < 5; i++) {  
                    Integer value = count.get("a");  
                    if (null == value) {  
                        count.put("a", 1);  
                    } else {  
                        count.put("a", value + 1);  
                    }  
                }  
                endLatch.countDown();  
            }  
        };  
        new Thread(task).start();  
        new Thread(task).start();  
        try {  
            endLatch.await();  
            System.out.println(count);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
    public static void demo2() {/*  
        final Map<String, Integer> count = new ConcurrentHashMap<>();  
        final CountDownLatch endLatch = new CountDownLatch(2);  
        Runnable task = new Runnable() {  
            @Override  
            public void run() {  
                Integer oldValue, newValue;  
                for (int i = 0; i < 5; i++) {  
                    while (true) {  
                        oldValue = count.get("a");  
                        if (null == oldValue) {  
                            newValue = 1;  
                            if (count.putIfAbsent("a", newValue) == null) {  
                                break;  
                            }  
                        } else {  
                            newValue = oldValue + 1;  
                            if (count.replace("a", oldValue, newValue)) {  
                                break;  
                            }  
                        }  
                    }  
                }  
                endLatch.countDown();  
            }  
        };  
        new Thread(task).start();  
        new Thread(task).start();  
      
        try {  
            endLatch.await();  
            System.out.println(count);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    */}  
}
